$(document).ready(function(){
    animate();
    
    setInterval(function(){
        refresh();
    }, 10*1000);
    
});

function animate(){
    var total = 0;
    var values = {};
    var widths = {};
    $(".bar_full").each(function(index){
        $(this).html("&nbsp;");
        values[index] = parseInt($(this).attr('value'),10);
        if (isNaN(values[index]) || values[index] == 0){
            values[index] = 0;
            $(this).parents("tr").find('.bar_votes').html("0");
            $(this).attr("class","bar_full bar_zero");
        }
        
    });
    
    for(var v in values){
        total += values[v];
    }
    
    $("#total_votes").html(total);
    
    for(var v in values){
        widths[v] = values[v]/total*100;
    }
    
    $(".bar_full").each(function(index){
        $(this).animate({width: widths[index]+"%"},500);
    });
}

function refresh(){
    $.post(getBaseURL()+"current_orders/popular/refresh",{},
    function(meals){
            console.log(meals)
        var i = 0;
        for(var meal in meals){
            var votes = meals[meal];           
            
            $("td.bar_votes").eq(i).html(votes);
            $("td.bar_empty .bar_full").eq(i).val(votes);
            
            i++;
        }
        animate();
    }, "json");
}